package _array

import org.junit.Assert
import org.junit.Test

/**
 * https://leetcode.cn/problems/minimum-size-subarray-sum/description/
 * https://programmercarl.com/0209.%E9%95%BF%E5%BA%A6%E6%9C%80%E5%B0%8F%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84.html
 *
 * 给定一个含有 n 个正整数的数组和一个正整数 target 。
 * 找出该数组中满足其总和大于等于 target 的长度最小的 子数组 [numsl, numsl+1, ..., numsr-1, numsr] ，并返回其长度。如果不存在符合条件的子数组，返回 0 。
 *
 * 输入：target = 7, nums = [2,3,1,2,4,3]
 * 输出：2
 *
 * 输入：target = 4, nums = [1,4,4]
 * 输出：1
 *
 * 输入：target = 11, nums = [1,1,1,1,1,1,1,1]
 * 输出：0
 */
class Test8 {
    @Test
    fun test_1() {
        val nums = intArrayOf(2, 3, 1, 2, 4, 3)
        val actual = Solution().minSubArrayLen(7, nums)
        val expect = 2
        Assert.assertEquals(expect, actual)
    }

    @Test
    fun test_2() {
        val nums = intArrayOf(1, 4, 4)
        val actual = Solution().minSubArrayLen(4, nums)
        val expect = 1
        Assert.assertEquals(expect, actual)
    }

    @Test
    fun test_3() {
        val nums = intArrayOf(1, 1, 1, 1, 1, 1, 1, 1)
        val actual = Solution().minSubArrayLen(11, nums)
        val expect = 0
        Assert.assertEquals(expect, actual)
    }

    class Solution {
        fun minSubArrayLen(target: Int, nums: IntArray): Int {
            /**
            left
            right
            sum
            subLen = max
            temp = max

            while(right from 0 to N){
            sum + right
            right++

            while(sum > = target){
            temp = right - left
            if(tmp < subLen){
            subLen = tmp
            }
            sum = sum - sum[left]
            left--
            }
            }

            if(subLen == max){
            return 0
            }ese{
            return subLen
            }
             */

            var left: Int = 0
            var right: Int = 0
            val end = nums.size - 1
            var subLen: Int = -1
            var temp: Int;
            var sum: Int = 0
            while (right <= end) {
                sum = sum + nums[right]
                right++

                while (sum >= target) {
                    temp = right - left
                    if (subLen == -1) {
                        subLen = temp
                    } else if (temp < subLen) {
                        subLen = temp
                    }
                    sum = sum - nums[left]
                    left = left + 1
                }
            }
            if (subLen == -1) {
                return 0
            } else {
                return subLen
            }
        }
    }
}